package com.songtech.server.frame.push;

import com.songtech.server.constant.KeysConstant;
import com.songtech.server.frame.protocal.analyse.Analyze;
import com.songtech.server.frame.utils.ByteBufUtils;
import com.songtech.server.utils.GetKeysUtils;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufUtil;
import io.netty.buffer.PooledByteBufAllocator;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelOutboundBuffer;
import io.netty.handler.codec.string.StringEncoder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


/**
 * Create By YINN on 2018/4/8 14:56
 * Description :
 */

@Service
public class PushToClient implements Push {

    @Autowired
    private Analyze analyze;

    private static Logger log = LoggerFactory.getLogger(PushToClient.class);

    private boolean flag = false;

    @Override
    public boolean push(String msg, String imei) {

        //获取管道
       Channel ch = ChannelCacheManager.getChannel(imei);

        ByteBuf buf = transStr2Buf(msg);

        //主动推送消息给客户端
        if (ch != null && ch.isActive() && ch.isWritable()) {

            System.out.println("已经写入管道:"+msg);

            ChannelFuture future = ch.writeAndFlush(buf);

            //重写future监听
            future.addListener(new ChannelFutureListener() {

                @Override
                public void operationComplete(ChannelFuture future) {
                    if (future.isSuccess()) {

                        //若成功
//                        future.

                        flag = true;

                    } else {


                        //若失败
                        Throwable cause = future.cause();

                        System.out.println(cause);

                        log.info(cause.getMessage());

                    }
                }

            });
        }

        return flag;
    }

    private ByteBuf transStr2Buf(String msg){


        ByteBuf byteBuf = Unpooled.buffer(1024);

        byteBuf.writeBytes(msg.getBytes());

        return byteBuf;

    }

}
